﻿<%@ Page Title="" Language="C#" MasterPageFile="~/DSS/Site.Master" AutoEventWireup="true"
    CodeBehind="Hybrid.aspx.cs" Inherits="DSS.DSS.Hybrid"  ValidateRequest="false"%>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="DSS.HybridClasses" %>    <%@ Import Namespace="Ext.Net" %>
    
<script runat="server">
    
    public static Boolean SavedDb { get; set; }
    //для вставки
    protected class ObjWithId
    {
        public Int32 Id { get; set; }
    }

    public static class CurrentColor//текущее множество
    {
        public static String Color { get; set; }//лвл мн-ва
        public static Int32 PreferenceId { get; set; }//ид мн-ва
        public static Int32 VarietiesCount { get; set; }//кол-во множеств пользователя
        public static Int32 CriterionCount { get; set; }//кол-во критериев
    }

    public class VarietyNew
    {
        public String Level { get; set; }
        public string Condition { get; set; }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!X.IsAjaxRequest)
        {

            var config = new MessageBoxConfig
            {
                Title = "LOADING", Message = "Do you want to load DB?", Closable = false, Icon = MessageBox.Icon.QUESTION, Buttons = MessageBox.Button.YESNO, MessageBoxButtonsConfig = new MessageBoxButtonsConfig
                {
                    Yes = new MessageBoxButtonConfig {Handler = "Hybrid.ClickedYes()", Text = "YES"},
                    No = new MessageBoxButtonConfig {Handler = "Hybrid.ClickedNo()", Text = "NO"}
                }
            };
            X.Msg.Show(config);
        }
    }


    [DirectMethod(Namespace = "Hybrid")]
    public void ClickedYes()
    {
        AddColumns();
        SavedDb = true;
    }

    [DirectMethod(Namespace = "Hybrid")]
    public void ClickedNo()
    {
    }



    // добавить колонки
    protected void AddColumns()
    {
        Grid.Listofpreferences.Clear();
        CurrentColor.CriterionCount = 0;
        CurrentColor.PreferenceId = -1;
        CurrentColor.VarietiesCount = 0;
        int mv;
        DataTable dt = GetDataTableForCriterias(out mv);
        for (var i = 1; i <= mv; ++i)
        {
            String str = String.Format(@"Value{0}", i);
            var field = new ModelField {Type = ModelFieldType.String, Name = str};//создать поле
            StoreCriterion.AddField(field, i + 3);
            var col = new Column();
            col.DataIndex = str;
            col.ID = str;
            col.Text = str;
            col.Width = 75; 
            col.Flex = 1;//создать колонку
            var tf = new TextField();//редактор для поля колонки
            Controls.Add(tf);
            col.SetEditor(tf);
            col.Editor.Add(tf);
            GridPanelCriteria.AddColumn(col);
        }

        var store = GridPanelCriteria.GetStore();
        store.DataSource = dt;// Hybrid.Grid.ReadFromDB();
        store.DataBind();
        int a;
        ComboBoxStore.DataSource = GetDataTableForComboBox(out a);
        ComboBoxStore.DataBind();

    }




    private readonly DataTable _dataTableSets = new DataTable();

    public DataTable GetDataTableForPreferenceSets()
    {
        _dataTableSets.Columns.Add("Id", typeof(int));
        _dataTableSets.Columns.Add("Name", typeof(string));
        _dataTableSets.Columns.Add("Value", typeof(string));
        return _dataTableSets;
    }
    
    public DataTable GetDataTableForCriterias(out int maxval)
    {
         if (String.IsNullOrEmpty(Context.Request.QueryString["id"]))
            throw new ArgumentNullException("GetDataTableForCriterias, query string is null or empty");
        var parentId = Context.Request.QueryString["id"];
       return Grid.GetDataTableForCriterias(parentId, out maxval);
    }


    public DataTable GetDataTableForComboBox(out int maxval)
    {
        if (String.IsNullOrEmpty(Context.Request.QueryString["id"]))
            throw new ArgumentNullException("GetDataTableForCriterias, query string is null or empty");
        var parentId = Context.Request.QueryString["id"];
        return Grid.GetDataTableForComboBox(parentId, out maxval);
    }

    //новое предпочтение
    protected void AddRowVariety(object sender, DirectEventArgs e)
    {
        var vn = new VarietyNew {Level = ComboBox1.Text};
        GridPanel2.GetStore().Insert(CurrentColor.VarietiesCount, vn);
        ++CurrentColor.VarietiesCount;
    }
    //заполняем множества

    protected void Cell_Click(object sender, DirectEventArgs e)
    {

            if (CurrentColor.PreferenceId == -1)//еще не выбрали множество
            {
                X.Msg.Alert("Error", "Chose Variety").Show();
                return;
            }
        var sm = GridPanelCriteria.GetSelectionModel() as CellSelectionModel;

        if (sm != null)
        {
            string str = string.Format("RecordID: {0}<br />Name: {1}<br />Value: {2}<br />Row: {3}<br />Column: {4}",
                sm.SelectedCell.RecordID, sm.SelectedCell.Name, sm.SelectedCell.Value,
                sm.SelectedCell.RowIndex, sm.SelectedCell.ColIndex);
            X.Msg.Notify("selected", str).Show();
        }
        for (int i = 0; i < Grid.Listofpreferences.Count; ++i)
            {
                var pr = Grid.Listofpreferences[i];
                //повторный клик, удалитacь
                if ((pr.CriteriaId == sm.SelectedCell.RowIndex) && (pr.SubId == sm.SelectedCell.ColIndex - 2)
                    && (CurrentColor.PreferenceId == pr.PreferenceId))
                {
                    Grid.Listofpreferences.Remove(pr);
                    GridPanelCriteria.GetStore().GetAt(sm.SelectedCell.RowIndex).Set(String.Format
                        (@"Value{0}", sm.SelectedCell.ColIndex - 2), sm.SelectedCell.Value.TrimStart('*'));
                    GridPanel2.GetStore().GetAt(CurrentColor.PreferenceId).Set
                        ("Condition", Grid.GetPreferenceString(CurrentColor.PreferenceId));
                    return;
                }
            }
        if (sm != null)
        {
            GridPanelCriteria.GetStore().GetAt(sm.SelectedCell.RowIndex).Set
                ("Value" + (sm.SelectedCell.ColIndex - 2), '*' + sm.SelectedCell.Value);
        
            Grid.SaveOnePreference(sm.SelectedCell.RowIndex,
                sm.SelectedCell.ColIndex - 2, CurrentColor.PreferenceId, sm.SelectedCell.Value, CurrentColor.Color);
        }

        GridPanel2.GetStore().GetAt(CurrentColor.PreferenceId).Set
                ("Condition", Grid.GetPreferenceString(CurrentColor.PreferenceId));

    }




    //очистить множества
    protected void ClearPreferences(object sender, DirectEventArgs e)
    {
        Grid.Listofpreferences.Clear();
    }
    //работа собственно
    protected void GetResult(object sender, DirectEventArgs e)
    {
        try
        {
            var g = new Grid();
            var var = new Variety(g);
            string str;
            if ((str = Grid.CheckUserPreferences()) == "") //чтоб все было
            {
                Grid.SaveAllPrfeferenceInDb(Convert.ToInt32(Context.Request.QueryString["id"]));
                var.MakeVariety(g);
                var.GetVarietyPoints(); //множества
                var.SortPointsForPareto();
                var.MakeAdjacencyMatrix(Convert.ToInt32(Context.Request.QueryString["id"]));
                if (!var.DetectCycles())
                {
                    var.GraphAnalysis();
                    var.SaveResult(Convert.ToInt32(Context.Request.QueryString["id"]));
                    X.Msg.Notify("Done", "No cycles").Show();
                }
            }
            else X.Msg.Notify("Error", str).Show();
        }
        catch (Exception)
        {
        }
    }



    protected void SaveChanges(object sender, DirectEventArgs e)
    {
        
    }


    protected void Cell_Color_Click(object sender, DirectEventArgs e)
    {

        {

            var sm = GridPanel2.GetSelectionModel() as CellSelectionModel;
            //выбор множества
            if (sm != null && sm.SelectedCell.ColIndex == 1)
            {
                sm.SelectedCell.ColIndex = 0;
                sm.UpdateSelection();
                return;
            }
            if (sm != null && sm.SelectedCell.ColIndex == 0)
            {
                //повторный клик, ничего не делаем
                if (CurrentColor.PreferenceId == sm.SelectedCell.RowIndex)
                    return;
                CurrentColor.PreferenceId = sm.SelectedCell.RowIndex;
                var str = sm.SelectedCell.Value;
                CurrentColor.Color = sm.SelectedCell.Value;
                X.Msg.Notify("Chosen variety", str).Show();
            }
            //очистка от *
            string grid1Json = e.ExtraParams["Grid1"];
            var grid1Data = JSON.Deserialize<Dictionary<string, string>[]>(grid1Json);
            for (int i = 0; i < grid1Data.Length; ++i)
            {
                ModelProxy record = GridPanelCriteria.GetStore().GetById(i);
                for (int j = 1; j <= grid1Data[i].Count - 3; ++j)
                {
                    if (grid1Data[i][String.Format(@"Value{0}", j)].Length != 0)
                    //  if (grid1Data[i][String.Format(@"Value{0}", j)][0] == '*')
                    {
                        record.BeginEdit();
                        grid1Data[i][String.Format(@"Value{0}", j)] = grid1Data[i][String.Format(@"Value{0}", j)].TrimStart('*');
                        record.Set(String.Format(@"Value{0}", j), grid1Data[i][String.Format(@"Value{0}", j)]);
                        record.EndEdit();
                        record.Commit();
                    }
                }
            }
            //заполнение *
            try
            {
                for (int i = 0; i < Grid.Listofpreferences.Count; ++i)
                    if (Grid.Listofpreferences[i].PreferenceId == CurrentColor.PreferenceId)
                    {
                        ModelProxy record = GridPanelCriteria.GetStore().GetById(Grid.Listofpreferences[i].CriteriaId);
                        record.BeginEdit();
                        record.Set(String.Format("Value{0}", Grid.Listofpreferences[i].SubId), "*" +
                            grid1Data[Grid.Listofpreferences[i].CriteriaId][String.Format("Value{0}", Grid.Listofpreferences[i].SubId)]);
                        record.EndEdit();
                    }
            }
            catch (Exception) { }
        }
        //   else


    }

    [DirectMethod(Namespace = "Hybrid")]
    public void Edit(int id, string field, string oldValue, string newValue, object customer)
    {
        const string message = "<b>Property:</b> {0}<br /><b>Field:</b> {1}<br /><b>Old Value:</b> {2}<br /><b>New Value:</b> {3}";
        X.Msg.Notify("Edit Record #" + id, string.Format(message, id, field, oldValue, newValue)).Show();
        GridPanelCriteria.GetStore().GetById(id).Commit();
        SavedDb = false;
    }

</script>
    

<%--<%@ Import Namespace="Hybrid" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>--%>
<asp:Content ID="Content1" ContentPlaceHolderID="Title" runat="server">Гибридный метод
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Header" runat="server">Гибридный метод
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
      <script type="text/javascript">
          var edit = function (editor, e) {
              if (e.value !== e.originalValue) {
                  window.Hybrid.Edit(e.record.data.ID, e.field, e.originalValue, e.value, e.record.data);
              }
          };
    </script>
    <ext:ResourceManager ID="ResourceManager1" runat="server" />
    <ext:GridPanel ID="GridPanelCriteria" runat="server" Title="Criterias" Height="350"
        Collapsible="true">
        <Store>
            <ext:Store ID="StoreCriterion" runat="server">
                <Model>
                    <ext:Model ID="Model1" runat="server" IDProperty="ID">
                        <Fields>
                            <ext:ModelField Name="ID" Type="Int" />
                            <ext:ModelField Name="Optimization" Type="String" />
                            <ext:ModelField Name="Name" Type="String" />
                        </Fields>
                    </ext:Model>
                </Model>
            </ext:Store>
        </Store>
        <ColumnModel ID="ColumnModel1" runat="server">
            <Columns>
          
                <ext:Column runat="server" Text="ID" DataIndex="ID" Width="35" />
                <ext:Column ID="OptCol" runat="server" Text="Optimization" DataIndex="Optimization">
                    <Editor>
                        <ext:TextField runat="server" />
                    </Editor>
                </ext:Column>
                <ext:Column runat="server" Text="Name" DataIndex="Name">
                    <Editor>
                        <ext:TextField runat="server" />
                    </Editor>
                </ext:Column>
           
            </Columns>
        </ColumnModel>
        <SelectionModel>
            <ext:CellSelectionModel ID="CellSelectionModel2" runat="server" Mode="Multi">
                <DirectEvents>
                    <Select OnEvent="Cell_Click">
                    </Select>
                </DirectEvents>
            </ext:CellSelectionModel>
        </SelectionModel>
        <View>
            <ext:GridView ID="GridView1" runat="server" StripeRows="true" TrackOver="true" EnableTextSelection="true" />
        </View>
        <Plugins>
            <ext:CellEditing ID="CellEditing1" runat="server" ClicksToEdit="2">
                <Listeners>
                    <Edit Fn="edit" />
                </Listeners>
            </ext:CellEditing>
        </Plugins>
    
    </ext:GridPanel>
    <ext:GridPanel ID="GridPanel2" runat="server" Title="Varieties" Height="300">
        <Store>
            <ext:Store ID="Store2" runat="server">
                <Model>
                    <ext:Model ID="Model2" runat="server" IDProperty="ID">
                        <Fields>
                            <ext:ModelField Name="Level" />
                            <ext:ModelField Name="Condition" />
                        </Fields>
                    </ext:Model>
                </Model>
            </ext:Store>
        </Store>
        <ColumnModel ID="ColumnModel2" runat="server">
            <Columns>
                <ext:Column ID="ColumnName" runat="server" Text="Name" DataIndex="Level">
                </ext:Column>
                <ext:Column ID="ColumnCondition" runat="server" Text="Condition" DataIndex="Condition"
                    Flex="5">
                    <Editor>
                        <ext:TextField ID="TextField3" runat="server">
                        </ext:TextField>
                    </Editor>
                </ext:Column>
            </Columns>
        </ColumnModel>
        <SelectionModel>
            <ext:CellSelectionModel ID="CellSelectionModel3" runat="server" Mode="Multi">
                <DirectEvents>
                    <Select OnEvent="Cell_Color_Click" >
                        <ExtraParams>
                            <ext:Parameter Name="Grid1" Value="Ext.encode(#{GridPanelCriteria}.getRowsValues({selectedOnly : false}))"
                                Mode="Raw" />
                        </ExtraParams>
                    </Select>
                </DirectEvents>
            </ext:CellSelectionModel>
        </SelectionModel>
        <View>
            <ext:GridView ID="GridView2" runat="server" StripeRows="false" TrackOver="true" Height="200" />
        </View>
        <BottomBar>
            <ext:Toolbar ID="Toolbar2" runat="server">
                <Items>
                    <ext:ToolbarFill ID="ToolbarFill2" runat="server" />
                    <ext:ComboBox ID="ComboBox1" 
            runat="server"
            Width="250"
            Editable="false"
            
            DisplayField="ScaleName"
            ValueField="ScaleName"
            QueryMode="Local"
            ForceSelection="true"
            TriggerAction="All"
            EmptyText="Select a state...">                        
            <Store>
                <ext:Store ID="ComboBoxStore" runat="server">
                    <Model>
                        <ext:Model ID="Model3" runat="server">
                            <Fields>
                                <ext:ModelField Name="ScaleName" />
                                <ext:ModelField Name="ScaleValue" />
                            </Fields>
                        </ext:Model>
                    </Model>            
                </ext:Store>
            </Store>
            <ListConfig>
                <ItemTpl ID="ItemTpl1" runat="server">
                    <Html>
						<div class="list-item">
							    <h3>{ScaleName}</h3>
							    {ScaleValue:ellipsis(15)}
						</div>
				    </Html>    
                </ItemTpl>
            </ListConfig>
        </ext:ComboBox>  
                    <ext:Button ID="AddRow" runat="server" Text="Add Row" Icon="Add">
                        <DirectEvents>
                            <Click OnEvent="AddRowVariety" />
                        </DirectEvents>
                    </ext:Button>
                    <ext:Button ID="Button3" runat="server" Text="Save" Icon="Disk">
                        <DirectEvents>
                            <Click OnEvent="GetResult" Single="false" />
                        </DirectEvents>
                    </ext:Button>
                </Items>
            </ext:Toolbar>
        </BottomBar>
    </ext:GridPanel>
</asp:Content>
